# -*- coding: utf-8 -*-
from flask import Blueprint, render_template, redirect, url_for, request
from flask_login import login_required
from models import Post
from app import db

posts = Blueprint('post', __name__, template_folder='templates')


@posts.route('/')
def index():
    posts = Post.query.order_by(Post.create_time.desc())
    return render_template('post/index.html', posts=posts)


@posts.route('/<id>')
@login_required
def detail(id):
    post = Post.query.get(id)
    return render_template('post/detail.html', post=post)


@posts.route('/add/', methods=['GET', 'POST'])
@login_required
def add():
    if request.method == 'POST':
        p = Post()
        p.title = request.form['title']
        p.content = request.form['content']
        p.keyword = request.form['keyword']
        db.session.add(p)
        db.session.commit()
        return redirect(url_for('post.index'))
    return render_template('post/add.html')


@posts.route('/delete/<int:id>')
@login_required
def delete(id):
    post = Post.query.get(id)
    db.session.delete(post)
    db.session.commit()
    return redirect(url_for('post.index'))


@posts.route('/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def edit(id):
    post = Post.query.get(id)
    if request.method == 'POST':
        post.title = request.form['title']
        post.content = request.form['content']
        post.keyword = request.form['keyword']
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('post.index'))
    return render_template('post/edit.html', post=post)
